package tdh.xt.controller;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import tdh.xt.common.utils.CookieUtil;
import tdh.xt.common.utils.FormatUtil;
import tdh.xt.common.utils.Md5Util;
import tdh.xt.common.utils.TokenUtil;
import tdh.xt.entity.Translater;
import tdh.xt.entity.po.User;
import tdh.xt.entity.vo.Page;
import tdh.xt.entity.vo.ResultDto;
import tdh.xt.enums.CustomResultCode;
import tdh.xt.service.UserService;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/*
* @Package tdh.xt.controller
* @Description UserController
* @Author RicarAN
* @Date 2021/6/15 16:07
* @Copyright (c) 2021,南京通达海科技股份有限公司 All Rights Reserved.
* @Version 1.0
* Modification History:
* Date                  Author      Version     Description
* ------------------------------------------------------------------
* 2021/6/15 16:07       RicarAN      1.0        UserController
*
*/
@Controller
public class UserController {

    @Resource(name = "userService")
    UserService userService;

    @Autowired
    Translater translater;

    /*
     * @description 登陆方法
     * @param yhid 用户id
	 * @param yhkl 用户kl，如果上次记住密码，则使用上一次记住的密码，否则对密码加密
	 * @param rememberYhid 是否记住用户名
	 * @param rememberYhkl 是否记住用户密码
	 * @param token 当前cookie里是否存在cookie，存在则尝试对比cookie内的用户名和密码
	 * @param session session
	 * @param response response
     * @return java.lang.String 是否登陆成功
     * @author RicarAN
     * @version 1.0
     * @date 2021/6/15 16:09
     */
    @RequestMapping(value = "/login.do", method = RequestMethod.GET)
    @ResponseBody
    public ResultDto login(@RequestParam("yhid") String yhid,
                        @RequestParam("yhkl") String yhkl,
                        @RequestParam(value = "rememberYhid", required = false) String rememberYhid,
                        @RequestParam(value = "rememberYhkl", required = false) String rememberYhkl,
                        @CookieValue(value = "token", required = false) String token,
                        HttpSession session,
                        HttpServletResponse response){
        //第一个条件是新用户登录，第二个是已经记住密码，但是用户使用新的账号登陆
        if (token == null || !yhid.equals(TokenUtil.getYhid(token))) {
            yhkl = Md5Util.getMd5String(yhkl);
        }
        User login = userService.login(yhid, yhkl);
        if (login == null) {
            //可能是同一个用户，但是用户没有使用记住的密码，而是使用原始密码，此时也应该加密后登录
            yhkl = Md5Util.getMd5String(yhkl);
            login = userService.login(yhid, yhkl);
            if (login == null) {
                return ResultDto.errorOf(CustomResultCode.USERNAME_OR_PASSWORD_ERROR);
            }
        }
        String newToken = TokenUtil.getToken(login);
        session.setAttribute("loginUser", login);
        List<Cookie> cookieList = new ArrayList<Cookie>();
        cookieList.add(new Cookie("token", newToken));
        if ("1".equals(rememberYhkl)) {
            cookieList.add(new Cookie("rememberYhid", "1"));
            cookieList.add(new Cookie("rememberYhkl", "1"));
        } else if ("1".equals(rememberYhid)) {
            cookieList.add(new Cookie("rememberYhid", "1"));
        }
        CookieUtil.setCookies(response, cookieList, 7 * 24 * 60 * 60);
        return ResultDto.okOf(CustomResultCode.LOGGING_SUCCESS, newToken);
    }

    /*
     * @description 删除一个用户
     * @param yhdm 用户代码
     * @return java.lang.String 是否删除成功
     * @author RicarAN
     * @version 1.0
     * @date 2021/6/15 16:11
     */
    @RequestMapping(value = "/delete.do", method = RequestMethod.POST)
    @ResponseBody
    public ResultDto deleteUser(@RequestParam("yhdm") String yhdm) {
        if (userService.deleteByYhdm(yhdm) == 1) {
            return ResultDto.okOf(CustomResultCode.DELETE_USER_SUCCESS);
        }
        return ResultDto.errorOf(CustomResultCode.DELETE_USER_FAILER);
    }

    /*
     * @description 注销用户
     * @param session session
	 * @param request request
	 * @param response response
     * @return java.lang.String 是否注销成功
     * @author RicarAN
     * @version 1.0
     * @date 2021/6/15 16:12
     */
    @RequestMapping(value = "/logout.do", method = RequestMethod.GET)
    @ResponseBody
    public ResultDto logout(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        session.invalidate();
        CookieUtil.removeAllLoginCookies(request, response);
        return ResultDto.okOf(CustomResultCode.LOGOUT_SUCCESS);
    }

    /*
     * @description 获取单个用户信息
     * @param yhdm 用户代码
     * @return java.lang.String 单个用户信息
     * @author RicarAN
     * @version 1.0
     * @date 2021/6/15 16:12
     */
    @RequestMapping(value = "/user.do", method = RequestMethod.GET)
    @ResponseBody
    public ResultDto user(@RequestParam("yhdm") String yhdm) {
        User user = userService.getUserFromYhdm(yhdm);
        if (user == null) {
            return ResultDto.errorOf(CustomResultCode.NO_USER_FOUNDED);
        }
        return ResultDto.okOf(CustomResultCode.FIND_ONE_USER, user);
    }

    /*
     * @description 更新或插入用户
     * @param user     更新或插入的用户
	 * @param isUpdate 标识是否是更新用户
     * @return java.lang.String 更新或插入用户是否成功
     * @author RicarAN
     * @version 1.0
     * @date 2021/6/15 16:14
     */
    @RequestMapping(value = "/insertOrUpdate.do", method = RequestMethod.POST)
    @ResponseBody
    public ResultDto insertOrUpdate(@RequestBody User user, @RequestParam boolean isUpdate) {
        user.setCsrq(FormatUtil.dateFormat(user.getCsrq(), "yyyy-MM-dd", "yyyyMMdd"));
        user.setDjsj(FormatUtil.formatCurrentDateTime("yyyy-MM-dd HH:mm:ss"));
        user.setDwdm("320100");
        if (isUpdate) {
            User dbUser = userService.getUserFromYhdm(user.getYhdm());
            if (dbUser == null) {
                return ResultDto.errorOf(CustomResultCode.NO_USER_FOUNDED);
            }
            if (!user.getYhkl().equals(dbUser.getYhkl())) {
                user.setYhkl(Md5Util.getMd5String(user.getYhkl()));
            }
            if (userService.updateByYhdm(user) == 1) {
                return ResultDto.okOf(CustomResultCode.UPDATE_USER_SUCCESS);
            }
            return ResultDto.errorOf(CustomResultCode.UPDATE_USER_FAILER);
        } else {
            user.setYhkl(Md5Util.getMd5String(user.getYhkl()));
            if (userService.hasYhdm(user.getYhdm())) {
                return ResultDto.errorOf(CustomResultCode.ALREADY_EXISTS_USER);
            }
            if (userService.insert(user) == 1) {
                return ResultDto.okOf(CustomResultCode.ADD_USER_SUCCESS);
            }
            return ResultDto.errorOf(CustomResultCode.ADD_USER_FAILER);
        }
    }

    /*
     * @description 获得xml格式的用户列表并返回
     * @param type 类型
	 * @param bmdmOrSearchText 搜索文本
	 * @param currentPage 当前页
	 * @param pageSize 分页大小
     * @return java.lang.String xml格式的用户列表
     * @author RicarAN
     * @version 1.0
     * @date 2021/6/23 13:48
     */
    @RequestMapping(value = "/xmlStringUserList.do", produces = {"text/xml; charset=utf-8"})
    @ResponseBody
    public String xmlUserList(@RequestParam(value = "type", required = false) String type,
                          @RequestParam(value = "param", required = false) String bmdmOrSearchText,
                          @RequestParam(value = "start", defaultValue = "1") Integer currentPage,
                          @RequestParam(value = "limit", defaultValue = "40") Integer pageSize) {
        Page<User> page = new Page<User>(currentPage, pageSize);
        if (StringUtils.isEmpty(type)) {
            return userService.getGridUserList(page);
        } else if ("search".equalsIgnoreCase(type)) {
            return userService.gridSearch(bmdmOrSearchText, page);
        } else {
            return userService.getGridUserListFromBmdmWithPage(bmdmOrSearchText, page);
        }
    }

    /*
     * @description 获得xml格式的用户
     * @param yhdm  用户代码
     * @return java.lang.String xml格式的用户
     * @author RicarAN
     * @version 1.0
     * @date 2021/6/23 13:49
     */
    @RequestMapping(value = "/xmlStringUser.do", produces = {"text/xml; charset=utf-8"})
    @ResponseBody
    public String xmlUser(@RequestParam("yhdm") String yhdm) {
        return userService.getXmlUserFromYhdm(yhdm);
    }

    /*
     * @description 获得用户列表，会在jsp中组装完成返回xml格式
     * @param type 类型
	 * @param bmdmOrSearchText 搜索文本
	 * @param currentPage 开始数据
	 * @param pageSize 分页大小
     * @return org.springframework.web.servlet.ModelAndView modelAndView
     * @author RicarAN
     * @version 1.0
     * @date 2021/6/23 13:51
     */
    @RequestMapping(value = "/xmlJspUserList.do")
    public ModelAndView testXmlUserList(@RequestParam(value = "type", required = false) String type,
                                        @RequestParam(value = "param", required = false) String bmdmOrSearchText,
                                        @RequestParam(value = "start", defaultValue = "1") Integer currentPage,
                                        @RequestParam(value = "limit", defaultValue = "40") Integer pageSize) {
        Page<User> page = new Page<User>(currentPage, pageSize);
        if (StringUtils.isEmpty(type)) {
            userService.getGridUserList(page);
        } else if ("search".equalsIgnoreCase(type)) {
            userService.gridSearch(bmdmOrSearchText, page);
        } else {
            userService.getGridUserListFromBmdmWithPage(bmdmOrSearchText, page);
        }
        ModelAndView modelAndView = new ModelAndView("xmlUserList");
        modelAndView.addObject("page", page);
        return modelAndView;
    }

    /*
     * @description 获得用户，会在jsp中组装完成后返回xml
     * @param yhdm 用户代码
	 * @param mode model
     * @return java.lang.String xmlUserList.jsp
     * @author RicarAN
     * @version 1.0
     * @date 2021/6/23 13:52
     */
    @RequestMapping("/xmlJspUser.do")
    public String testXmlUser(@RequestParam("yhdm") String yhdm, Model model) {
        User user = userService.getUserFromYhdm(yhdm);
        List<User> userList = new ArrayList<User>(1);
        userList.add(user);
        Page<User> page = new Page<User>(1, 40);
        page.setTotalCount(1);
        page.setData(userList);

        model.addAttribute("page", page);
        return "xmlUserList";
    }

    @RequestMapping("/userList.do")
    public String userList(HttpSession session, Model model) {
        User user = (User) session.getAttribute("loginUser");
        Assert.notNull(user, "未登录");
        translater.translate(user);
        model.addAttribute("loginUser", user);
        return "userList";
    }
}